package org.zxt.web.nio;

import java.util.concurrent.*;

public class DefaultAsyncRunner implements AsyncRunner {
    private BlockingQueue<Runnable> queue;
    private ThreadPoolExecutor executor;

    public DefaultAsyncRunner(int cap, int coreSize, int maxSize, int alive){
        queue = new LinkedBlockingQueue<>(cap);
        executor = new ThreadPoolExecutor(coreSize, maxSize, alive, TimeUnit.SECONDS, queue, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("web-thread");
                System.out.println("--------------------->"+thread.getName());
                return thread;
            }
        });
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
    }

    @Override
    public void closeAll() {
        executor.shutdown();
    }

    @Override
    public void exec(HTTPSession session) {
        try{
            executor.execute(session);
        } catch (RejectedExecutionException e){
            session.close();
        }
    }
}
